﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using MxWeiXinPF.BLL;

namespace MxWeiXinPF.Web.admin.wxapp
{
    public partial class wxappshopDetail : Web.UI.ManagePage
    {

        int id = 0;

        wxapp_appinfo dzpBll = new wxapp_appinfo();
        BLL.wxapp_userList appUserBll = new wxapp_userList();
        protected void Page_Load(object sender, EventArgs e)
        {
            id = MyCommFun.RequestInt("id", 0);
            if (id == 0)
            {
                JscriptMsg("传输参数不正确！", "back");
                return;
            }
            if (!dzpBll.Exists(id))
            {
                JscriptMsg("小程序不存在或已被删除！", "back");
                return;
            }

            if (!Page.IsPostBack)
            {


                ShowInfo(id);
            }
        }



        #region 赋值操作=================================

        private void ShowInfo(int id)
        {

            Model.wxapp_appinfo model = dzpBll.GetModel(id);
            lblwxappName.Text = model.wxappName;
            lblwxappBrief.Text = model.wxappBrief;
            imgtyQRPic.ImageUrl = model.tyQRPic;
            lblwxappRequirement.Text = model.wxappRequirement;

            lblshelfTime.Text = model.shelfTime.Value.ToString("yyyy-MM-dd");

            //示意图
            IList<Model.mx_attachInfo> attachlist = new List<Model.mx_attachInfo>();
            BLL.mx_attachInfo attachBll = new mx_attachInfo();
            attachlist = attachBll.GetModelList("wxapp_appinfo_shili", "wxapp_appinfo", id);

            rptAlbumList.DataSource = attachlist;
            rptAlbumList.DataBind();

            //判断该小程序是否可以购买
            if (model.status != 1)
            {
                btnSubmit.Text = "未上线";
                btnSubmit.Enabled = false;
            }

            //判断是否购买过了
            int user_id = GetAdminInfo().id;
            DataTable oldBuyInfo = appUserBll.GetModelByWxappIdAndUserId(id, user_id);
            if (oldBuyInfo != null && oldBuyInfo.Rows.Count > 0)
            {
                DataRow dr = oldBuyInfo.Rows[0];
                //已购买,并且还未过期，不能再次购买
                DateTime usedvalidDate = MyCommFun.Obj2DateTime(dr["usedvalidDate"],DateTime.Parse("1990-1-1"));

                if (usedvalidDate == DateTime.Parse("1990-1-1")  || usedvalidDate > DateTime.Now)
                {
                    btnSubmit.Text = "已购买";
                    btnSubmit.Enabled = false;
                     
                }
                else
                {
                    btnSubmit.Text = "确认续费";
                }
            }

        }

        #endregion




        /// <summary>
        /// 购买
        ///  若以后加上在线支付，则逻辑有所调整，1 在支付成功之前， 插入order订单表， 
        /// 2 支付成功后，再order表状态改掉,插入wxapp_userList表的status=0
        /// 3、审核通过后再把wxapp_userList表的status=1
        ///  
        /// 现逻辑， 第1步和第2步合并。
        ///  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            Model.wxapp_appinfo appModel = dzpBll.GetModel(id);
            //判断该小程序是否可以购买
            if (appModel.status != 1)
            {
                JscriptMsg("未上线，不能购买", "back");
                return;

            }

            Model.wxapp_userList appUser = new Model.wxapp_userList();

            Model.manager user = GetAdminInfo();
            int user_id = user.id;
            int ustatus = 0;//状态（0申请中，1审核通过，2审核失败），100 首次购买；200续费
            DataTable oldBuyInfo = appUserBll.GetModelByWxappIdAndUserId(id, user_id);
            if (oldBuyInfo != null && oldBuyInfo.Rows.Count > 0)
            {
                DataRow dr = oldBuyInfo.Rows[0];
                //已购买,并且还未过期，不能再次购买
                DateTime usedvalidDate = MyCommFun.Obj2DateTime(dr["usedvalidDate"]);
                ustatus = MyCommFun.Obj2Int(dr["usedStatus"]);//购买的状态
                if (usedvalidDate == DateTime.Parse("1990-1-1") || usedvalidDate > DateTime.Now)
                {
                    JscriptMsg("已购买，不能再次购买", "back");
                    return;
                }
                else
                {
                    ustatus = 200;
                }
            }
            else
            {
                ustatus = 100;
            }

            BLL.wxapp_buyOrders orderBll = new wxapp_buyOrders();
            Model.wxapp_buyOrders order = new Model.wxapp_buyOrders();
            DateTime now = DateTime.Now;

            if (ustatus == 100)
            {
                //如果是第一次购买
                //1 初始化用户的的小程序数据
                appUser.userId = user_id;
                appUser.wxappId = id;
                appUser.applyTime = now;
                appUser.status = 0;//申请中
                appUser.price = appModel.currPrice;

                //2 订单数据
                order.wxappId = id;
                order.userId = user_id;
                order.username = user.user_name;
                order.storeName = user.storeName;
                order.wxappName = appModel.wxappName;
                order.price = appModel.currPrice;
                order.status = 1;
                order.orderNo = Utils.Number(10);
                order.tradeNo = "";
                order.paymentType = "outline";//下线支付
                order.paymentStatus = 1;//支付成功
                order.paymentTime = now;
                order.createTime = now;
                order.createPersonId = user_id;
                order.buyType = 1;
                order.remark = "第一次购买小程序" + appModel.wxappName;
                int retappUserId = appUserBll.Add(appUser);
                if (retappUserId > 0)
                {
                    int retOrderId = orderBll.Add(order);

                    AddAdminLog(MXEnums.ActionEnum.Invalid.ToString(), "用户(user_id=" + user_id + ")购买了小程序（id=" + id + ")"); //记录日志//1e2124dd04e11d01b9df2865f85944be
                    JscriptMsg("小程序购买成功！", "wxappshop.aspx");

                }

            }
            else
            {
                //续费
                //1 获取用户的的小程序数据，然后 有效期延长，价格累加
                appUser = appUserBll.GetModel(id, user_id);
                appUser.validDate = DateTime.Now.AddYears(appModel.validYear.Value);
                appUser.price = appUser.price + appModel.currPrice;

                //2 订单数据
                order.wxappId = id;
                order.userId = user_id;
                order.username = user.user_name;
                order.storeName = user.storeName;
                order.wxappName = appModel.wxappName;
                order.price = appModel.currPrice;
                order.status = 1;
                order.orderNo = Utils.Number(10);
                order.tradeNo = "";
                order.paymentType = "outline";//下线支付
                order.paymentStatus = 1;//支付成功
                order.paymentTime = now;
                order.createTime = now;
                order.createPersonId = user_id;
                order.buyType = 2;
                order.remark = "续费小程序" + appModel.wxappName;
                bool retappUserId = appUserBll.Update(appUser);
                if (retappUserId)
                {
                    int retOrderId = orderBll.Add(order);
                    AddAdminLog(MXEnums.ActionEnum.Invalid.ToString(), "用户(user_id=" + user_id + ") 续费了小程序（id=" + id + ")"); //记录日志//1e2124dd04e11d01b9df2865f85944be
                    JscriptMsg("小程序续费成功！", "wxappshop.aspx");
                }


            }

        }




    }
}